package admin_menu_api

import (
	"blog_go/global"
	"blog_go/models"
	"blog_go/models/res"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"gorm.io/gorm"
)

func (AdminMenuApi) MenuDel(c *gin.Context) {
	var delReq models.DeleteRequest
	if err := c.ShouldBind(&delReq); err != nil {
		logrus.Error(err)
		panic(err)
	}
	var menuList []models.MenuModel
	affected := global.DB.Find(&menuList, delReq.IdList).RowsAffected
	if affected == 0 {
		panic("数据都不存在")
	}
	var delCount int64
	err := global.DB.Transaction(func(tx *gorm.DB) error {
		// 删除菜单图片关联表
		if err := tx.Model(&menuList).Association("ImageList").Clear(); err != nil {
			return err
		}
		// 删除菜单
		db := tx.Delete(&menuList)
		delCount = db.RowsAffected
		err := db.Error
		if err != nil {
			return err
		}

		return nil
	})
	if err != nil {
		logrus.Error(err)
		panic(err)
	}
	res.Ok(fmt.Sprintf("删除的条数%d", delCount), true, c)
}
